package com.dongdongshop.serviceImpl;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.Cart;
import com.dongdongshop.pojo.TbOrder;
import com.dongdongshop.pojo.TbOrderItem;
import com.dongdongshop.service.TbOrderService;
import com.dongdongshop.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@com.alibaba.dubbo.config.annotation.Service
public class TbOrderServiceImpl  implements TbOrderService {
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
     private RedisTemplate redisTemplate;
    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;
    @Override
    public Map<Object,Object>  addInfo(TbOrder order) {
    //得到购物车数据
        Map <Object,Object> map =new HashMap<>();
        List<Cart> cartList = (List<Cart>)redisTemplate.boundHashOps("cartList").get(order.getUserId());
        double money = 0;
        IdWorker idWorker = new IdWorker(0,0);
        String payorderid = Long.toString(idWorker.nextId());
        for(Cart cart:cartList){
            long orderId = idWorker.nextId();
            TbOrder tbOrder = new TbOrder();//新创建订单对象
            tbOrder.setOrderId(orderId);//订单Id
            tbOrder.setUserId(order.getUserId());//用户名
            tbOrder.setPaymentType(order.getPaymentType());//支付类型
            tbOrder.setStatus("1");//状态：未付款
            tbOrder.setCreateTime(new Date());//订单创建日期
            tbOrder.setUpdateTime(new Date());//订单修改日期
            tbOrder.setReceiverAreaName(order.getReceiverAreaName());//地址
            tbOrder.setReceiverMobile(order.getReceiverMobile());//手机号
            tbOrder.setReceiver(order.getReceiver());//收获人
            tbOrder.setSourceType(order.getSourceType());//订单来源
            tbOrder.setSellerId(cart.getSellerId());//商家ID
            //循环购物车明细
            for(TbOrderItem orderItem : cart.getOrderItemList()){
                orderItem.setId(idWorker.nextId());
                orderItem.setOrderId(orderId);//订单Id
                orderItem.setSellerId(cart.getSellerId());
                money +=orderItem.getTotalFee().doubleValue();//金额累加
                tbOrderItemMapper.insertSelective(orderItem);
            }
            tbOrder.setPayment(new BigDecimal(money));
            tbOrder.setPayOrderid(payorderid);
            tbOrderMapper.insertSelective(tbOrder);
        }
        map.put("payorderid",payorderid);
        map.put("money",money);
        map.put("mingcheng","测试");
        map.put("body","暂无描述");
//      redisTemplate.boundHashOps("cartList").delete(order.getUserId());
        return map;
        }
}
